<template>
	<view class="">
		<u-sticky>
			<view class="header_warp bg-white p-2 flex justify-between align-center shadow">
				<image class="logo" src="@/static/img2/home/logo.png" mode="aspectFit"></image>
				<view class="head_button flex align-center text-white">
					<image src="@/static/img2/home/home_search.png" mode="aspectFit" @tap="goPages('/subPages/home/home_search/home_search')"></image>
					<text class="mx-2"></text>
					<image src="@/static/img2/home/message.png" mode="aspectFit" @click="goPages('/pages/message/index')"></image>
					<text class="mx-2"></text>
					<image src="@/static/img2/home/my.png" mode="" @click="goPages('/pages/my/index')"></image>
				</view>
			</view>
		</u-sticky>
		<view class="bg-white py-2 px-4 h_100">
			<view v-if="!info" class="p-2 mt-3"><u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty></view>
			<view v-else>
				<view class="h3 font-weight-bolder">{{ info.title }}</view>
				<view class="flex justify-between my-2">
					<view class="flex">
						<view class="font_24 c_9 mr-2 flex warp">
							<text>来源：</text>
							<view class="cont_text">{{ info.source }}</view>
						</view>
						<view class="font_24 c_9 flex warp">
							<text>发表时间：</text>
							<view class="cont_text">{{ info.create_at }}</view>
						</view>
					</view>
					<view class="share bg_main text-white font-small rounded_10 text-center mt" @click="share">海报</view>
				</view>
				<u-overlay :show="shareShow" @click="shareClose" opacity="0.7">
					<view class="m-auto position-relative">
						<view class="share_close p" v-show="closeShow" @click="shareClose"><u-icon name="close" color="#666" size="28"></u-icon></view>
						<!-- 350 * _this.powerw, 600 * _this.powerw -->
						<view class="" :style="{ width: 310 * powerw + 'px', height: 580 * powerw + 'px' }" @longtap="transpond">
							<canvas class="canvas" canvas-id="myCanvas" style="width: 100%;height: 100%;position: absolute; top: -1000px; left: -1000px;"></canvas>
							<image :src="shareImg" class="cardImage" mode="" style="width: 100%;height: 100%;"></image>
						</view>
						<view class="font text-white text-center mt-2">长按图片可以保存转发哦~</view>
						<!-- <view class="flex justify-around">
							<button class="saveimg_btn bg_main text-white font-sm font-weight-bold" @click="saveImage">保存</button>
							<button class="saveimg_btn bg_main text-white font-sm font-weight-bold" @click="transpond">转发</button>
						</view> -->
					</view>
				</u-overlay>
				<view class="mt-2 cont">
					<u-parse :content="content(info.content)" copyLink lazyLoad pauseVideo previewImg :selectable="true" showImgMenu class="font-size:36rpx"></u-parse>
				</view>
				<view class="font_24_2 c_6 py-5">
					特别声明：索比光伏网所转载其他网站内容,出于传递更多信息而非盈利之目的,同时并不代表赞成其观点或证实其描述,内容仅供参考。版权归原作者所有,若有侵权,请联系我们删除。
				</view>
			</view>
		</view>
		<view class="bg-white p-2 mt-3" v-if="newsLists.length >= 1">
			<view class="c_6 font-md flex align-center">
				<u-icon name="thumb-up" color="#959595" size="28"></u-icon>
				<text style="color: #959595;" class="ml-1">相关推荐</text>
			</view>
			<view class=""><news-list :list="newsLists"></news-list></view>
			<u-loadmore :status="status" color="#E5E5E5" lineColor="#E5E5E5" dashed line />
		</view>
		<!-- 底部点赞/收藏/转发操作栏 -->
		<view class="fixed-bottom bg-white shadow py-2">
			<favorite-bottom :numdata="info.new_operate" :new-id="info.id" :type="info.type" :platform="info.platform" @loginSuccess="loginSuccess"></favorite-bottom>
		</view>
		<u-back-top :scroll-top="scrollTop"></u-back-top>
		<!-- 裁剪分享时图片的canvas -->
		<div v-if="shareShow">
			<canvas canvas-id="canvas" style="position: absolute; top: -1000px; left: -1000px;width: 225px; height: 180px;"></canvas>
		</div>
	</view>
</template>

<script>
import { getnewsDetail, snecRecommend, snecShare } from '@/api/home/home.js';
import util from '@/common/js/util.js';
import newsList from '@/components/news_list.vue';
import favoriteBottom from '@/components/favorite_bottom/favorite_bottom.vue';
export default {
	components: { newsList, favoriteBottom },
	data() {
		return {
			info: {},
			infoId: '',
			exhibitionId: '',
			platform: 0,
			page: 1,
			status: 'loadmore',
			suo: true,
			newsLists: [],
			scrollTop: 0,
			shareShow: false,
			closeShow:false,
			powerw: 0,
			shareImg: null
		};
	},
	computed: {
		content(val) {
			return function(val) {
				return val.replace(/<p/gi, '<p class="cont"');
			};
		}
	},
	onLoad(option) {
		// console.log(option);
		this.infoId = option.id;
		this.exhibitionId = option.exhibitionId;
		this.platform = option.platform; //首页新闻类型

		this.getInfo();
		// 分享
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		let message = uni.getSystemInfoSync(); //获取手机信息
		this.powerw = message.windowWidth / 375;
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	//分享到聊天
	onShareAppMessage(res) {
		if (this.info.imglist || this.info.img_path) {
			let shareMessage = {
				title: this.info.title,
				path: '/subPages/exhibition/news/detail?id=' + this.infoId + '&exhibitionId=' + this.exhibitionId + '&platform=' + this.platform,
				imageUrl: this.info.imglist || this.info.img_path
			};
			return new Promise((resolve, reject) => {
				uni.showLoading({
					title: '请求分享数据中...',
					icon: 'none'
				});
				util.makeCanvas(shareMessage.imageUrl)
					.then(imgPath => {
						// console.log('===', imgPath);
						uni.hideLoading();
						resolve({
							title: shareMessage.title,
							path: shareMessage.path,
							imageUrl: imgPath
						});
					})
					.catch(err => {
						// console.log('err', err);
						uni.hideLoading();
						resolve(shareMessage);
					});
			});
		} else {
			return {
				title: this.info.title,
				path: '/subPages/exhibition/news/detail?id=' + this.infoId + '&exhibitionId=' + this.exhibitionId + '&platform=' + this.platform, //界面路径
				imageUrl: 'https://yunz.solarbe.com/member/img/solarbe.jpg'
				// '/static/img2/home/logo.jpg'
			};
		}
	},
	// 分享到朋友圈
	onShareTimeline() {
		return {
			title: this.info.title,
			path: '/subPages/exhibition/news/detail?id=' + this.infoId + '&exhibitionId=' + this.exhibitionId + '&platform=' + this.platform, //界面路径
			imageUrl: this.info.imglist || this.info.img_path || '/static/img2/home/company_head.png'
		};
	},
	onReachBottom() {
		if (this.suo) {
			//定义个小锁，当没有数据时锁住suo
			this.status = 'loading';
			this.page = ++this.page;
			setTimeout(() => {
				this.recommend();
			}, 1000);
		}
	},
	methods: {
		getInfo() {
			let msg = {
				id: this.infoId,
				zhanhui_id: this.exhibitionId,
				uid: uni.getStorageSync('userInfo').userId || '',
				platform: this.platform
			};
			getnewsDetail(msg)
				.then(res => {
					// console.log(res);
					if (res.code == 0) {
						this.info = res.data;
						this.recommend();
					} else {
						uni.$u.toast(res.msg);
					}
				})
				.catch(err => {
					console.log('获取新闻详情失败', err);
				});
		},
		recommend() {
			let msg = {
				id: this.infoId,
				page: this.page,
				type: this.platform,
				topickeywords: this.info.topickeywords
			};
			snecRecommend(msg).then(res => {
				if (res.code == 0) {
					this.newsLists.push(...res.data);
					if (res.data.length == 0) {
						this.status = 'nomore';
						this.suo = false;
					} else if (res.data.length < 10) {
						this.status = 'nomore';
						this.suo = false;
					} else {
						this.status = 'loadmore';
						this.suo = true;
					}
				} else {
					uni.$u.toast(res.msg);
				}
			});
			uni.hideLoading();
		},
		// 分享海报
		share() {
			uni.showLoading({
				title: '分享图片正在生成中...'
			});
			// let msg = {
			// 	id: this.infoId,
			// 	type: this.platform
			// };
			// snecShare(msg).then(res => {
			// 	console.log('分享', res);

			this.shareShow = true;
			this.drawPoster();
			// });
		},
		async drawPoster() {
			let _this = this;
			const ctx = uni.createCanvasContext('myCanvas', this);
			let bg = 'https://yunz.solarbe.com/upload/code_png/background.png';
			let code = _this.info.orcode;
			ctx.draw();
			ctx.save();
			// 显示背景图片
			await uni
				.getImageInfo({
					src: bg
				})
				.then(res => {
					if (res[1].errMsg == 'getImageInfo:ok') {
						ctx.save();
						ctx.drawImage(res[1].path, 0, 0, 310 * _this.powerw, 610 * _this.powerw);
						ctx.restore();
					} else {
						uni.$u.toast('海报生成失败');
					}
				});
			// 时间
			ctx.setFillStyle('#333'); //文字颜色：默认黑色
			ctx.textAlign = 'center'; // 设置位置
			ctx.font = 'normal 14px Microsoft Yahei'; // 字体样式
			ctx.fillText(_this.info.create_at, 160 * _this.powerw, 110 * _this.powerw);
			// 标题
			ctx.setFillStyle('#333');
			ctx.textAlign = 'left';
			ctx.font = 'bold 20px Microsoft Yahei';
			_this.textPrewrap(ctx, _this.info.title, 20 * _this.powerw, 140 * _this.powerw, 28 * _this.powerw, 255 * _this.powerw, 2);
			// 内容
			ctx.setFillStyle('#818181');
			ctx.textAlign = 'left';
			ctx.font = '600 14px Microsoft Yahei';
			_this.textPrewrap(ctx, _this.info.smalltext, 20 * _this.powerw, 200 * _this.powerw, 22 * _this.powerw, 255 * _this.powerw, 11);
			// 横线
			ctx.beginPath();
			ctx.moveTo(20 * _this.powerw, 450 * _this.powerw);
			ctx.lineTo(290 * _this.powerw, 450 * _this.powerw);
			ctx.setStrokeStyle('#E0E0E0');
			ctx.stroke();
			// 左边文字
			ctx.setFillStyle('#bfbfbf');
			ctx.textAlign = 'left';
			ctx.font = '400 11px Microsoft Yahei';
			_this.textPrewrap(ctx, '长按右侧二维码访问小程序阅读更多', 20 * _this.powerw, 490 * _this.powerw, 15 * _this.powerw, 180 * _this.powerw, 2);
			// ctx.fillText('长按右侧二维码访问小程序阅读更多', 20, 370 * _this.powerw);
			ctx.setFillStyle('#bfbfbf');
			ctx.textAlign = 'left';
			ctx.font = '400 11px Microsoft Yahei';
			_this.textPrewrap(ctx, '也可保存图片到相册', 20 * _this.powerw, 520 * _this.powerw, 15 * _this.powerw, 150 * _this.powerw, 2);
			// ctx.fillText('也可保存图片到相册', 20, 400 * _this.powerw);
			// 二维码
			await uni
				.getImageInfo({
					src: this.info.orcode
				})
				.then(result => {
					if (result[1].errMsg == 'getImageInfo:ok') {
						ctx.save();
						ctx.drawImage(result[1].path, 210 * _this.powerw, 470 * _this.powerw, 70 * _this.powerw, 70 * _this.powerw); //绘制图
						ctx.restore();
						// ctx.draw(true)
					} else {
						uni.showToast({
							title: '海报生成失败',
							duration: 2000,
							icon: 'none'
						});
					}
				});
			ctx.draw(true, ret => {
				setTimeout(() => {
					uni.canvasToTempFilePath(
						{
							canvasId: 'myCanvas',
							success: res => {
								this.shareImg = res.tempFilePath;
								// console.log(this.shareImg);
								this.closeShow = true;
								uni.hideLoading();
							},
							fail: err => {
								uni.$u.toast('海报生成失败');
								console.log('海报生成失败', err);
								uni.hideLoading();
								// this.shareShow = false;
							}
						},
						this
					);
				}, 1000);
			});
		},
		/**
		ctx： 画布的上下文环境
		content： 需要绘制的文本内容
		drawX： 绘制文本的x坐标
		drawY： 绘制文本的y坐标
		lineHeight：文本之间的行高
		lineMaxWidth：每行文本的最大宽度
		lineNum：最多绘制的行数
		*/
		textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
			var drawTxt = ''; // 当前绘制的内容
			var drawLine = 1; // 第几行开始绘制
			var drawIndex = 0; // 当前绘制内容的索引
			// 判断内容是否可以一行绘制完毕
			if (ctx.measureText(content).width <= lineMaxWidth) {
				ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
			} else {
				for (var i = 0; i < content.length; i++) {
					drawTxt += content[i];
					if (ctx.measureText(drawTxt).width >= lineMaxWidth) {
						if (drawLine >= lineNum) {
							ctx.fillText(content.substring(drawIndex, i) + '..', drawX, drawY);
							break;
						} else {
							ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
							drawIndex = i + 1;
							drawLine += 1;
							drawY += lineHeight;
							drawTxt = '';
						}
					} else {
						// 内容绘制完毕，但是剩下的内容宽度不到lineMaxWidth
						if (i === content.length - 1) {
							ctx.fillText(content.substring(drawIndex), drawX, drawY);
						}
					}
				}
			}
		},
		// 保存图片
		// saveImage() {
		// 	uni.saveImageToPhotosAlbum({
		// 		filePath: this.shareImg,
		// 		success: res => {
		// 			uni.$u.toast('保存成功');
		// 		}
		// 	});
		// },
		// 转发
		transpond() {
			wx.showShareImageMenu({
				path: this.shareImg,
				success: res => {
					// console.log(res);
					this.shareShow = false;
					wx.showToast({
						title: '操作成功！',
						icon: 'none',
						duration: 2000
					});
				},
				fail: err => {
					console.log(err);
					// this.saveImage();
					wx.showToast({
						title: err,
						icon: 'none',
						duration: 2000
					});
				}
			});
		},
		// 快捷登录后更新点赞收藏状态
		loginSuccess() {
			this.getInfo();
		},
		// 关闭海报
		shareClose(){
			this.shareShow = false
		}
	}
};
</script>

<style lang="scss" scoped>
page {
	background-color: $color2 !important;
}
.header_warp {
	height: 78rpx;
	.logo {
		width: 158rpx;
		height: 31rpx;
	}
	.head_button {
		image {
			width: 39rpx;
			height: 39rpx;
		}
		text {
			font-weight: 100;
			border-left: 1px solid #fff;
			width: 1rpx;
			height: 27rpx;
		}
	}
}
::v-deep .cont {
	color: #333333;
	font-size: 36rpx !important;
	line-height: 1.8;
	letter-spacing: 3.5rpx;
	font-weight: 400;
}
.share {
	height: 35rpx;
	width: 85rpx;
	line-height: 35rpx;
}
.share_close {
	position: absolute;
	top: -35rpx;
	right: -35rpx;
	background-color: #f6f4f4;
	border-radius: 100%;
	z-index: 9999;
}
.saveimg_btn {
	width: 200rpx;
	border-radius: 35rpx;
}
.cardImage {
	border-radius: 30rpx;
}

.bottom_share {
	width: 100%;
}
.cont_text {
	max-width: 200rpx;
}
</style>
